<script setup>
import { View, UploadFilled } from "@element-plus/icons-vue";
import { ref, reactive } from "vue";
import { formatTime } from "@/utils/format";
import { getFarmerApplyDetail, addFarmerApply } from "@/api/farmerApplication";
import { upload, deleteFile } from "@/api/file";
import { openFilePreview } from "@/utils/kkFileView";
import { auditFarmerApply } from "@/api/farmerApplication";

// 抽屉显隐
const visibleDrawer = ref(false);
// 存储申请数据
const applicationDetail = ref({});
// 区别是查看还是申请
const Tag = ref("");
const fileList = ref([]); // 上传文件列表
const emit = defineEmits(["success"]);
const handleOpen = async (row, tag) => {
  visibleDrawer.value = true;
  applicationDetail.value = { ...row };
  Tag.value = tag;
};

defineExpose({
  handleOpen,
});

const statusMap = [
  { label: "待审核", value: 0, type: "info" },
  { label: "通过", value: 1, type: "success" },
  { label: "驳回", value: 2, type: "danger" },
];

// 绑定表单对象
const formRef = ref(null);
// 表单验证规则
const formRules = reactive({
  realName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度需在2-20个字符之间", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "姓名只能包含中文或英文",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证件号", trigger: "blur" },
    {
      pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的18位身份证号码",
      trigger: "blur",
    },
  ],
});

// 记录文件对象
const fileMap = ref(null);
// 记录文件名字
const fileName = ref("");

// 文件状态改变时调用
const onUploadFile = (file) => {
  fileMap.value = file.raw;
  fileName.value = file.name;
};

// 点击文件预览时调用
const onPreview = async (file) => {
  const formData = new FormData();
  formData.append("file", file.raw, file.name);
  const res = await upload(formData);
  const url = res.data.data;
  openFilePreview(url);
  // 停止2秒
  await new Promise((resolve) => setTimeout(resolve, 2000));
  // 删除临时文件
  await deleteFile(url);
};
// 提交申请
const submit = async () => {
  // 表单预校验
  await formRef.value.validate();
  if (!fileList.value.length) {
    ElMessage({
      message: "请上传申请证明",
      type: "warning",
    });
    return;
  }

  const formData = new FormData();
  formData.append("file", fileMap.value, fileName.value);
  // 提交申请文件
  const res = await upload(formData);
  const url = res.data.data;

  const data = {
    realName: applicationDetail.value.realName,
    idCard: applicationDetail.value.idCard,
    farmerProof: url,
    applicationContent: applicationDetail.value.applicationContent,
  };

  const res2 = await addFarmerApply(data);
  ElMessage({
    message: "提交成功",
    type: "success",
  });
  emit("success");
  handleCancel();

  if (res2.data.code != 200) {
    // 删除图片
    await deleteFile(url);
  }
};

// 关闭抽屉
const handleCancel = () => {
  visibleDrawer.value = false;
  applicationDetail.value = {};
  data.value = { applicationId: "", status: 0, auditRemark: "" };
  fileList.value = [];
};
</script>

<template>
  <div>
    <!-- 抽屉 -->
    <el-drawer
      v-model="visibleDrawer"
      :title="Tag == 'detail' ? '查看申请详情' : '农户申请'"
      direction="rtl"
      size="50%"
    >
      <el-card style="max-width: 100%">
        <el-form
          ref="formRef"
          :model="applicationDetail"
          :rules="formRules"
          label-width="100px"
          style="margin-top: 20px"
          @close="handleCancel"
        >
          <el-form-item label="状态" v-if="Tag == 'detail'">
            <el-tag :type="statusMap[applicationDetail.status].type">
              {{ statusMap[applicationDetail.status].label }}
            </el-tag>
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input
              v-model="applicationDetail.realName"
              :disabled="Tag == 'detail'"
              style="width: 50%"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证件号" prop="idCard">
            <el-input
              v-model="applicationDetail.idCard"
              :disabled="Tag == 'detail'"
              style="width: 50%"
              placeholder="请输入身份证件号"
            ></el-input>
          </el-form-item>

          <el-form-item label="申请证明" v-if="Tag == 'add'">
            <el-upload
              class="upload-demo"
              drag
              :limit="1"
              :on-change="onUploadFile"
              :on-preview="onPreview"
              :auto-upload="false"
              v-model:file-list="fileList"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">请上传 <em>农户申请证明</em></div>
            </el-upload>
          </el-form-item>
          <el-form-item label="申请证明" v-if="Tag == 'detail'">
            <a>
              <el-button
                type="primary"
                @click="openFilePreview(applicationDetail.farmerProof)"
                :icon="View"
                >查看</el-button
              >
            </a>
          </el-form-item>
          <el-form-item label="申请时间" v-if="Tag == 'detail'">
            <el-input
              :value="formatTime(applicationDetail.applicationTime)"
              disabled
              style="width: 50%"
            ></el-input>
          </el-form-item>
          <el-form-item label="申请说明">
            <el-input
              v-model="applicationDetail.applicationContent"
              :disabled="Tag == 'detail'"
              :autosize="{ minRows: 2, maxRows: 6 }"
              type="textarea"
            ></el-input>
          </el-form-item>

          <el-form-item label="审核意见" v-if="Tag == 'detail'">
            <el-input
              v-model="applicationDetail.auditRemark"
              disabled
              :autosize="{ minRows: 2, maxRows: 6 }"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="Tag == 'add'">
            <el-button type="primary" @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-drawer>
  </div>
</template>

<style scoped>
:deep(.el-drawer__header) {
  margin-bottom: 5px;
}
.upload-demo {
  width: 100%;
}
</style>
